/*
 * @Author: 刘经标 2604132672@qq.com
 * @Date: 2025-04-12 17:50:34
 * @LastEditors: 刘经标 2604132672@qq.com
 * @LastEditTime: 2025-04-15 15:20:23
 * @FilePath: /ai-backend/src/controllers/chat.controller.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Request, Response } from 'express';
import axios from 'axios';
import { config } from '../config/env.js';
import { logger } from '../utils/logger.js';

export const chatHandler = async (req: Request, res: Response) => {
  console.log('收到的请求头:', req.headers);
  console.log('使用的API Key:', config.DEEPSEEK_API_KEY); // 确保.env已加载

  try {
    const response = await axios.post(
      'https://api.deepseek.com/v1/chat/completions',
      {
        model: "deepseek-chat",
        messages: req.body.messages // 确保直接转发消息体
      },

      {
        timeout: 40000,
        headers: {
          'Authorization': `Bearer ${config.DEEPSEEK_API_KEY}`, // 关键点
          'Content-Type': 'application/json'
        }
      }
    );
    res.json(response.data);
  } catch (error: any) {
    console.error('完整错误详情:', error.response?.data || error.message);
    res.status(500).json({ 
      error: 'AI服务暂时不可用',
      details: error.response?.data?.error?.message 
    });
  }
};